﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WeChatParking.Core.BLL
{
    public class Enterprise
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="OrderFields"></param>
        /// <param name="isDesc"></param>
        /// <returns></returns>
        public List<Entity.Enterprise> Get(string filter, string OrderFields = "", bool isDesc = false)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                try
                {
                    string sql = "select * from Enterprise";
                    if (filter.Length > 0)
                        sql += "  where  " + filter;
                    if (OrderFields.Length > 0)
                    {
                        if (isDesc)
                            sql += "   ORDER BY  " + OrderFields + "  DESC";
                        else
                            sql += "   ORDER BY  " + OrderFields;
                    }
                    return dbContext.GetListBySql<Entity.Enterprise>(sql, null).ToList();
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex, "获取物业数据");
                    return null;
                }
            }
        }
        public Entity.Enterprise Get(int ID)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                return dbContext.Get<Entity.Enterprise>(ID, null);
            }
        }
        public Entity.Enterprise Get(string Enterprise_Code)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                var precidate = new { Enterprise_Code = Enterprise_Code };
                return dbContext.GetList<Entity.Enterprise>(precidate, null).FirstOrDefault();
            }
        }
        public string Update(Entity.Enterprise val, string openUser)
        {
            var old = this.Get(val.ID);
            val.Enterprise_Code = old.Enterprise_Code;
            val.create_time = old.create_time;
            val.create_user = old.create_user;
            val.update_user = openUser;
            val.update_time = DateTime.Now;
            using (var dbContext = Repository.DbContext.Create())
            {
                if (dbContext.Update(val))
                    return "";
                else
                    return "失败";
            }
        }
        /// <summary>
        /// 是否存在代码
        /// </summary>
        /// <param name="RoleName"></param>
        /// <returns></returns>
        public bool ExistsCode(string Enterprise_Code)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                var precidate = new { Enterprise_Code = Enterprise_Code };
                return dbContext.Count<Entity.Enterprise>(precidate, null) > 0;
            }
        }
        /// <summary>
        /// 是否存在名
        /// </summary>
        /// <param name="RoleName"></param>
        /// <returns></returns>
        public bool ExistsName(string Enterprise_Name)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                var precidate = new { Enterprise_Name = Enterprise_Name };
                return dbContext.Count<Entity.Enterprise>(precidate, null) > 0;
            }
        }
        /// <summary>
        /// 添加企业/物业
        /// </summary>
        /// <param name="val"></param>
        /// <param name="openUser"></param>
        /// <returns></returns>
        public int Add(Entity.Enterprise val, string openUser)
        {
            int newId = -1;
            if (this.ExistsName(val.Enterprise_Name))
                return newId;
            else
            {
                if (this.ExistsCode(val.Enterprise_Code))
                    return newId;
                else
                {

                    val.create_time = DateTime.Now;
                    val.create_user = openUser;
                    val.update_time = DateTime.Now;
                    val.update_user = openUser;
                    using (var dbContext = Repository.DbContext.Create())
                    {
                        newId = dbContext.Insert(val);
                        if (openUser == "admin" && val.Enterprise_FCode == "0")
                        {
                            //是管理员并且添加的是根节点---需要添加角色，和用户 默认用户名是企业代码密码也是企业代码
                            Entity.Role role = new Entity.Role();
                            Entity.User_info user = new Entity.User_info();
                            role.RoleName = "管理员";
                            string PermissionID = "";
                            foreach (var item in Core.BLL.Permission.Get(""))
                                PermissionID += item.ID.ToString() + ",";
                            PermissionID = PermissionID.TrimEnd(',');
                            role.PermissionID = PermissionID;
                            role.EnterpriseID = newId;
                            role.create_time = DateTime.Now;
                            role.create_user = openUser;
                            role.update_time = DateTime.Now;
                            role.update_user = openUser;
                            role.version = 0;
                            int roelID = dbContext.Insert(role);
                            var bll = new Core.BLL.LoginUser();
                            user.UserName = val.Enterprise_Code;
                            user.UserCode = val.Enterprise_Code;
                            user.UserPhone = val.Contact_phone;
                            user.Wx_UserID = 0;
                            user.EnterpriseID = newId;
                            user.RoleID = roelID;
                            user.EnterpriseCode = val.Enterprise_Code;
                            user.create_time = DateTime.Now;
                            user.create_user = openUser;
                            user.update_time = DateTime.Now;
                            user.update_user = openUser;
                            user.version = 0;
                            user.UserLogPwd = bll.EncodePasswod(user.UserCode, user.UserCode);
                            dbContext.Insert(user);
                        }
                    }
                }
            }
            return newId;

        }

        public string Delete(int ID)
        {
            using (var dbContext = Repository.DbContext.Create())
            {
                var old = this.Get(ID);
                if (old.Enterprise_FCode == "0")
                    return "父级物业不允许删除";
                var predicate = new { ID = ID };
                bool success = dbContext.Delete<Entity.Enterprise>(predicate, null);
                if (success)
                    return string.Empty;
                return "删除失败";
            }
        }
        /// <summary>
        /// 企业
        /// </summary>
        /// <param name="ID"></param>
        /// <returns></returns>
        public List<Entity.Enterprise> EnterpriseQuery(int ID)
        {
            if (ID > 0)
            {
                List<Entity.Enterprise> list = new List<Entity.Enterprise>();
                var en = this.Get(ID);//根节点
                list.Add(en);

                var en1List = this.Get(String.Format("  Enterprise_FCode='{0}'", en.Enterprise_Code),"");//一级节点
                if (en1List.Count > 0)
                {
                    foreach (var item1 in en1List)
                    {
                        list.Add(item1);
                        var en2List = this.Get(String.Format("  Enterprise_FCode='{0}'", item1.Enterprise_Code),"");//二级节点
                        if (en2List.Count > 0)
                        {
                            foreach (var item2 in en2List)
                            {
                                list.Add(item2);
                                var en3List = this.Get(String.Format("  Enterprise_FCode='{0}'", item2.Enterprise_Code), "");//三级节点
                                if (en3List.Count > 0)
                                {
                                    foreach (var item3 in en3List)
                                    {
                                        list.Add(item3);
                                        var en4List = this.Get(String.Format("  Enterprise_FCode='{0}'", item3.Enterprise_Code), "");//四级节点
                                        if (en4List.Count > 0)
                                        {
                                            foreach (var item4 in en4List)
                                            {
                                                list.Add(item4);
                                                var en5List = this.Get(String.Format("  Enterprise_FCode='{0}'", item4.Enterprise_Code), "");//五级节点
                                                if (en5List.Count > 0)
                                                {
                                                    foreach (var item5 in en5List)
                                                    {
                                                        list.Add(item5);
                                                        var en6List = this.Get(String.Format("  Enterprise_FCode='{0}'", item5.Enterprise_Code), "");//六级节点
                                                        if (en6List.Count > 0)
                                                            foreach (var item6 in en6List)
                                                                list.Add(item6);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return list;
            }
            else
                return this.Get("", "");//admin


        }

    }
}
